import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Dialog, DialogTitle, DialogContent, Button } from '@mui/material';

const AddPopulationDialog = ({ open, onClose, fetchData }) => {
    const [numberOfIndividuals, setNumberOfIndividuals] = useState(0);
    const [previousNumberOfIndividuals, setPreviousNumberOfIndividuals] = useState(0);
    const [massOfIndividuals, setMassOfIndividuals] = useState(0);
    const [averageMass, setAverageMass] = useState('');
    const [averageSize, setAverageSize] = useState('');
    const [dateTime, setDateTime] = useState(new Date());
    const [previousDateTime, setPreviousDateTime] = useState(new Date());
    const [populationFed, setPopulationFed] = useState("");
    const [currentPool, setCurrentPool] = useState({name: '', id: 0});
    const [populations, setPopulations] = useState([]);
    const [mortality, setMortality] = useState(0);
    const [previousAm, setPreviousAm] = useState(0);
    const [pool, setPool] = useState(false);
    const [equipments, setEquipments] = useState([]);
    const [equipmentId, setEquipmentId] = useState(0);
    const [comment, setComment] = useState("");
    const [count, setCount] = useState(0);


    const handleInputChange = (setter) => (event) => {
        setter(event.target.value);
    };

    useEffect(()=> {
        fetchPreviousData();
        fetchEquipments();
    }, [populationFed])

    useEffect(() => {
        setCount(previousAm - mortality)
    },[previousAm, mortality, populationFed])

    const fetchEquipments = async () => {
        try {
            const headers = {
                'Authorization': `Bearer ${localStorage.getItem('access')}`,
            };
            const response = await axios.get(`${process.env.REACT_APP_API_BASE_URL}/equipment?free=true`, {headers});
            setEquipments(response.data.equipments);
            //setEquipmentId(response.data.equipments[0].eid)
        } catch (error) {
            console.error('Error fetching equipments:', error);
        }
    };


    const fetchPopulations = async () => {
        try {
            const headers = {
                'Authorization': `Bearer ${localStorage.getItem('access')}`,
            };
            const response = await axios.get(`${process.env.REACT_APP_API_BASE_URL}/population?active=true`, { headers });
            setPopulations(response.data.populations);
        } catch (error) {
            console.error('Error fetching populations:', error);
        }
    };

    const fetchPreviousData = async () => {
        try {
            const headers = {
                'Authorization': `Bearer ${localStorage.getItem('access')}`,
            };
            const response = await axios.get(`${process.env.REACT_APP_API_BASE_URL}/population_growth?population=${populationFed}&last=true`, { headers });
            const previousData = response.data.populationGrowth
            console.log(previousData[0].number_of_individuals == null? previousData[0].start_count :previousData[0].number_of_individuals)
            setPreviousAm(previousData[0].number_of_individuals == null? previousData[0].start_count :previousData[0].number_of_individuals)
            setCurrentPool({name: previousData[0].ename, id: previousData[0].eid })

            setPreviousDateTime(previousData[0].date_time == null?formatToLocalDatetime(new Date(previousData[0].startdate)): formatToLocalDatetime(new Date(previousData[0].date_time)));

        } catch (error) {
            console.error('Error fetching previous data:', error);
        }
    };

    const handleAverageMassChange = (event) => {
        setAverageMass(event.target.value);
    };

    const handleAverageSizeChange = (event) => {
        setAverageSize(event.target.value);
    };

    const handleMortalityChange = (event) => {
        setMortality(event.target.value);
    };

    
    const calculateTotalMass = () => {
        return ((previousAm - mortality) * averageMass / 1000).toFixed(2); // Convert grams to kg
    };

    const transplantPopulation = async () => {
        if(pool){
            changePool();
        }
        if (window.confirm("Вы уверены, что хотите пересадить популяцию?")) {
           setPool(true)
        }
    };
    const formatToLocalDatetime = (date) => {
        const tzOffset = date.getTimezoneOffset() * 60000; // offset in milliseconds
        const localISOTime = new Date(date - tzOffset).toISOString().slice(0, 16);
        return localISOTime;
    };
    function changePool(){
        const headers = {
            'Authorization': `Bearer ${localStorage.getItem('access')}`,
        };
        console.log(currentPool)
        const newPopulation = {
            "pid": populationFed,
            "equipment_id": equipmentId,
            "eid": currentPool.id,
        };
        console.log(newPopulation)
        axios.post(`${process.env.REACT_APP_API_BASE_URL}/pool`, newPopulation, { headers });
        onClose();
    }


    useEffect(() => {
        fetchPopulations();
        fetchEquipments();
        setDateTime(formatToLocalDatetime(new Date()))
        setPool(false)
        fetchPreviousData()
    }, [open]);

    useEffect(() => {
        setNumberOfIndividuals(previousNumberOfIndividuals + (massOfIndividuals - mortality));
    }, [massOfIndividuals, mortality, previousNumberOfIndividuals]);

    const addPopulation = async () => {
        try {
            const newPopulation = {
                "number_of_individuals": previousAm - mortality,
                "average_mass": averageMass,
                "average_size": averageSize,
                "id_population": populationFed,
                "date_time": dateTime,
                "mortality": mortality, 
               "mass_of_individuals": calculateTotalMass(),
            };
            const headers = {
                'Authorization': `Bearer ${localStorage.getItem('access')}`,
            };
            await axios.post(`${process.env.REACT_APP_API_BASE_URL}/population_growth`, newPopulation, { headers });
            fetchData();
            fetchPreviousData();
            onClose();
        } catch (error) {
            console.error('Error adding new population:', error);
        }
    };

    return (
        <Dialog open={open} onClose={onClose} sx={{ '& .MuiDialog-paper': { width: '80%', maxWidth: 'none' } }}>
            <DialogTitle sx={{
                                        fontFamily: 'Montserrat', fontWeight: 'bolder'}}>Добавить новые данные</DialogTitle>
            <DialogContent>
                <div>
                    <div className='input-table-container'>
                    <div style={{ display: 'grid', gridTemplateColumns: "0.4fr 1fr 0.4fr 1fr", gap: '20px' }}>
                            <label>Популяция</label>
                            <select
                                value={populationFed}
                                onChange={handleInputChange(setPopulationFed)}
                                className="input-form-table"
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            >
                             <option key={0} value={0}>Выберите популяцию</option>
                                {populations.map(equipment => (
                                    <option key={equipment.pid} value={equipment.pid}>{equipment.pcode + " " +equipment.pname}</option>
                                ))}
                            </select>
                            </div>
                        <div style={{ display: 'grid', gridTemplateColumns: "0.4fr 1fr 0.4fr 1fr", gap: '20px' }}>
                            <label>Падеж с последнего контроля, штук</label>
                            <input className='input-form-table'
                                type="number"
                                value={mortality}
                                onChange={handleMortalityChange}
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                            <label>Количество особей</label>
                            <input className='input-form-table'
                                type="number"
                                value={count}
                                readOnly
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                            <label>Средняя масса особей, грамм</label>
                            <input className='input-form-table'
                                type="number"
                                value={averageMass}
                                onChange={handleAverageMassChange}
                                required
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                            <label>Средний размер особи, см</label>
                            <input className='input-form-table'
                                type="number"
                                value={averageSize}
                                onChange={handleAverageSizeChange}
                                required
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                            <label>Текущая масса популяции, кг</label>
                            <input className='input-form-table'
                                type="number"
                                value={calculateTotalMass()}
                                readOnly
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                            <label>Текущий бассейн</label>
                            <input className='input-form-table'
                                type="text"
                                value={currentPool.name}
                                readOnly
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                            <label>Дата и время текущего контроля</label>
                            <input className='input-form-table'
                                type="datetime-local"
                                value={dateTime}
                                readOnly
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                            <label>Дата и время предыдущего контроля</label>
                            <input className='input-form-table'
                                type="datetime-local"
                                value={previousDateTime}
                                disabled
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                        </div>
                        {pool && <div style={{ display: 'grid', gridTemplateColumns: "0.4fr 1fr 0.4fr 1fr", gap: '20px' }}>
                            <label>Бассейн</label>
                            <select
                                value={equipmentId}
                                onChange={handleInputChange(setEquipmentId)}
                                className="input-form-table"
                                style={{ borderColor: 'orange', borderWidth: '2px', margin: 0, width: '100%' }}
                            >
                                {equipments.map(equipment => (
                                    <option key={equipment.eid} value={equipment.eid}>{equipment.ename}</option>
                                ))}
                            </select>
                            </div>}
                    </div>
                    <Button
                        onClick={addPopulation}
                        sx={{ margin: 3, width: '95%', color: 'white', borderRadius: '15px', backgroundColor: '#003AD0', '&:focus': { backgroundColor: '#003AD0' }, fontStyle: { fontColor: 'white', fontSize: 20, fontWeight: 'bolder', fontFamily: "Montserrat" } }}
                        variant={'contained'}
                        disabled={!(dateTime && averageMass && averageSize)}

                    >
                        Сохранить
                    </Button>
                    <Button
                        onClick={transplantPopulation}
                        sx={{ margin: 3, width: '95%', color: 'white', borderRadius: '15px', backgroundColor: pool? 'orange': '#009999', '&:focus': { backgroundColor: pool? 'orange': '#009999' }, fontStyle: { fontColor: 'white', fontSize: 20, fontWeight: 'bolder', fontFamily: "Montserrat" } }}
                        variant={'contained'}
                    >
                        Пересадить популяцию полностью
                    </Button>
                </div>
            </DialogContent>
        </Dialog>
    );
};

export default AddPopulationDialog;
